package com.hrt.manage.product.controllor;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.lf5.util.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.ProType;
import com.hrt.bean.ProductInfor;
import com.hrt.bean.ProductStatu;
import com.hrt.bean.ResourceType;
import com.hrt.bean.Resources;
import com.hrt.bean.UserVO;
import com.hrt.bean.UsersInfor;
import com.hrt.manage.product.service.ProInforService;
import com.hrt.manage.product.service.ProtypeService;
import com.hrt.manage.resource.service.ResourceService;
import com.hrt.manage.sequence.service.SequenceService;
import com.hrt.util.PageUtils;
import com.hrt.util.WebParams;
import com.hrt.util.upload.Plupload;
import com.hrt.util.upload.UploadUtil;

@Controller
@RequestMapping("/manage/proInfor")
public class ProInforController extends BaseController<ProductInfor> {

	@Autowired
	private ProtypeService protypeService;

	@Autowired
	private ProInforService proInforService;

	@Autowired
	private ResourceService resourceService;

	

	private List<ProType> proTypes;

	private List<Map<String, Object>> productStatus;

	protected ProductInfor product;

	private Long typeId;

	/**
	 * 文本上传路径
	 */
	private String textFileDir = "product/text/";

	@Autowired
	private UploadUtil uploadUtil;

	@Autowired
	private SequenceService sequenceService;

	/**
	 * 图片上传路径
	 */
	private static String imageFileDir =WebParams.PRODUCT_IMAGE_PATH;

	/**
	 * 视频上传路径
	 */
	private static String videoFileDir = WebParams.PRODUCT_VIDEO_PATH;

	public ProInforController() {
		// proTypes=this.getProTypes();
	}

	public Long getTypeId() {
		return typeId;
	}

	public void setTypeId(Long typeId) {
		this.typeId = typeId;
	}

	public List<ProType> getProTypes() {

		proTypes = protypeService.loadTypes();

		return proTypes;
	}

	public void setProTypes(List<ProType> proTypes) {
		this.proTypes = proTypes;
	}

	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map<String, PageUtils<ProductInfor>> queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "typeId", required = false) Long typeId,
			HttpServletRequest request) {
		Map<String, PageUtils<ProductInfor>> resultMap = new HashMap<String, PageUtils<ProductInfor>>();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);
		List<ProductInfor> resultList = new ArrayList();
		setTotalCount(proInforService.totalCount());
		this.typeId = typeId;
		if (this.typeId == null || this.typeId == -1) {
			resultList = proInforService.queryByPage(getPageIndex(),
					getPageSize());
		} else {
			resultList = proInforService.queryByProType(typeId, pageIndex,
					pageSize);
		}
		setList(resultList);

		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}

	/**
	 * 
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		view.setViewName("manage/product/list");
		list = proInforService.queryByPage(getPageIndex(), getPageSize());
		productStatus = this.getProductStatus();
		setTotalCount(proInforService.totalCount());
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		view.addObject("proTypes", getProTypes());
		view.addObject("pageResult", page);
		view.addObject("productStatus", productStatus);
		// request.getSession().setAttribute("pageResult", page);
		return view;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();

		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			proInforService.deleteById(idArr);

			return idArr;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("productDetail") ProductInfor product,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		System.out.println("save");

		System.out.println(product.getProCode());
		System.out.println(product.getProName());
		System.out.println(product.getDescription());
		UserVO manager = this.getOnlineManager(request, response);
		product.setCreatorId(manager.getUserId());
		if (product.getTypeId() != null) {
			ProType ptype = this.protypeService
					.getTypeByid(product.getTypeId());
			product.setProType(ptype);
			// ptype.getProductList().add(product);
		}
		System.out.println("getTypeId" + product.getTypeId());
		product.setCreatorName(manager.getLoinName());
		product.setEditorId(manager.getUserId());
		product.setEditor(manager.getLoinName());
		product.setEditTime(new java.sql.Date(new java.util.Date().getTime()));
		this.proInforService.saveProduct(product);
		try {
			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) String proId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (proId != null && !"".equals(proId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + proId);
			product = this.proInforService.getProductByid(new Long(proId));
			if (product != null) {
				map = transBean2Map(product);
				// for (Iterator<Map.Entry> itr = map.entrySet().iterator(); itr
				// .hasNext();) {
				// Map.Entry entry = itr.next();
				// System.out.println(entry.getKey().toString());
				// System.out.println(entry.getValue().toString());
				// }
			}

		}
		return map;

	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("protypeDetail") ProductInfor pro,
			HttpServletRequest request, HttpServletResponse response) {

		System.out.println("update");
		System.out.println(product.getProCode());
		System.out.println(product.getProName());
		System.out.println(product.getId());
		System.out.println(product.getDescription());

		try {
			this.product = proInforService.getProductByid(pro.getId());
			this.product.setProCode(pro.getProCode());
			this.product.setProName(pro.getProName());
			this.product.setUnit(pro.getUnit());
			product.setIsdemo(pro.getIsdemo());
			if (pro.getTypeId() != null) {
				ProType ptype = this.protypeService
						.getTypeByid(pro.getTypeId());
				product.setProType(ptype);
				// ptype.getProductList().add(product);
			}

			this.product.setFactory(pro.getFactory());
			// this.product.setRule(pro.getRule());

			UserVO manager = this.getOnlineManager(request, response);
			product.setGrown(pro.getGrown());
			this.product.setDescription(pro.getDescription());
			this.product.setEditorId(manager.getUserId());
			this.product.setEditor(manager.getLoinName());
			this.product.setEditTime(new java.sql.Date(new java.util.Date()
					.getTime()));
			proInforService.udateProduct(this.product);
			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/queryByProType")
	public ModelAndView queryByProType(
			@RequestParam(value = "typeId", required = true) Long typeId) {

		ModelAndView view = new ModelAndView();
		view.setViewName("manage/product/list");
		this.typeId = typeId;
		productStatus = this.getProductStatus();
		List list = proInforService.queryByProType(typeId);
		setList(list);
		setTotalCount(new Long(list.size()));
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		Map map = view.getModel();
		view.addObject("pageResult", page);
		view.addObject("proTypes", getProTypes());
		view.addObject("productStatus", productStatus);
		view.addObject("typeId", typeId);
		return view;

	}

	public ProductInfor getProduct() {

		return product;
	}

	public void setProduct(ProductInfor product) {
		this.product = product;
	}

	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, Object> add(
			@RequestParam(value = "id", required = false) Long typeId,
			HttpServletRequest request) {
		product = new ProductInfor();
		

		Map<String, Object> map = BaseController.transBean2Map(product);

		return map;

	}
	
	
	@RequestMapping(value = "/queryPrefixCodeByType")
	@ResponseBody
	public String queryPrefixCodeByType(@RequestParam(value="typeId")Long typeId)
	{
		if (typeId != null && !"".equals(typeId)) {
			ProType proType = protypeService.getTypeByid(typeId);
			if(proType.getTypeCode()!=null && !"".equals(proType.getTypeCode())){
				String typeCode=proType.getTypeCode();
				String seqNum=typeCode+"_"+this.sequenceService.getNextSequence(ProductInfor.class);
				System.out.println("***************"+seqNum);
				return seqNum;
			}
		}
		return null;
	}
	
	@RequestMapping(value = "/loadResouce")
	@ResponseBody
	public Map showResouce(
			@RequestParam(value = "id", required = true) Long proId,
			@RequestParam(value = "resType", required = false) Integer resType) {
		List list = new ArrayList();
		ModelAndView view = new ModelAndView();

		
		list = resourceService.getProductResource(proId, resType);
		setTotalCount(new Long(list.size()));
		this.setList(list);
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		Map<String, Object> result = BaseController.transBean2Map(page);
		// view.addObject("proTypes", getProTypes());
		result.put("proId", proId);
		result.put("pageResult", page);
		System.out.println("-------------------resource------------------------");
		System.out.println(list.size());
		
		return result;
	}

	@RequestMapping(value = "/showResouce")
	@ResponseBody
	public Map showResouce(
			@RequestParam(value = "id", required = true) Long proId,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "pageIndex", required = false) Integer  pageIndex,
			@RequestParam(value = "resType", required = false) Integer resType) {
		List list = new ArrayList();
		ModelAndView view = new ModelAndView();

		if(pageIndex==null){
			pageIndex=1;
		}
		if(pageSize==null){
			pageSize=8;
		}
		
		setPageIndex(pageIndex);
		setPageSize(pageSize);

		if (resType.intValue() == 0) {
			System.out.println(resType);
		}
		if (resType.intValue() == 1) {
			System.out.println(resType);
		}

		if (resType.intValue() == 2) {
			System.out.println(resType);
		}
		
		
		list = resourceService.getProductResource(proId,
				ResourceType.PRODUCT_RESOURCE, resType,getPageIndex(), getPageSize());
		setTotalCount(this.resourceService.countResourceByProductId(proId));
		this.setList(list);
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		Map<String, Object> result = BaseController.transBean2Map(page);
		// view.addObject("proTypes", getProTypes());
		result.put("proId", proId);
		result.put("pageResult", page);
		System.out.println("-------------------resource------------------------");
		System.out.println(list.size());
		
		return result;
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(Plupload plupload, HttpServletRequest request,
			HttpServletResponse response) {
		// System.out.println(plupload.getChunk() + "===" + plupload.getName() +
		// "---" + plupload.getChunks());
		// 资源类型,0图片，1视频，2文本等
		File dir = null;
		Integer resType = Integer.parseInt(request.getParameter("resType")==null?"0":request.getParameter("resType").toString());
		Long proId=Long.parseLong(request.getParameter("proId")==null?"0":request.getParameter("proId").toString());
		System.out.println("----resType="+resType);
		System.out.println("----proId="+proId);
		ProductInfor product=this.proInforService.getProductByid(proId);
		plupload.setRequest(request);
		// 文件存储路径
		
		if (resType.intValue() == 0) {
			dir = new File(plupload.getRequest().getSession()
					.getServletContext().getRealPath("/")
					+ imageFileDir);
		}
		if (resType.intValue() == 1) {
			dir = new File(plupload.getRequest().getSession()
					.getServletContext().getRealPath("/")
					+ videoFileDir);
		}

		if (resType.intValue() == 2) {
			dir = new File(plupload.getRequest().getSession()
					.getServletContext().getRealPath("/")
					+ textFileDir);
		}
		System.out.println(dir.getPath());
        if(product!=null){
		try {
			// 上传文件
			File file = uploadUtil.upload(plupload, dir);
			// 判断文件是否上传成功（被分成块的文件是否全部上传完成）
			if (UploadUtil.isUploadFinish(plupload)) {
				
				
				if (file != null && file.exists()) {
					String fileName=file.getName();
					String path=file.getPath();
					String accessDir=new String();
					if (resType.intValue() == 0) {
						 accessDir=new String(WebParams.DO_MAIN+WebParams.PRODUCT_IMAGE_PATH+fileName);
					}
					if (resType.intValue() == 1) {
						 accessDir=new String(WebParams.DO_MAIN+WebParams.PRODUCT_VIDEO_PATH+fileName);
					}

					if (resType.intValue() == 2) {
						 accessDir=new String(WebParams.DO_MAIN+WebParams.PRODUCT_VIDEO_PATH+fileName);
					}
					
					System.out.println("file be uploaded is "+accessDir);
					saveResource(file, resType,product,accessDir);

					return "success";
				}

			}
		
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "fail";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "fail";
		}
        }

		return "fail";
	}

	private void saveResource(File file, Integer resType,ProductInfor product, String accessDir) {
		// TODO Auto-generated method stub
		
		String fileName = file.getName();
		Resources resource = new Resources();
		resource.setResType(resType);
		/**
		 * 1 产品 2 礼品
		 */
		resource.setProId(product.getId());
		resource.setResName(file.getName());
		resource.setIsgift(ResourceType.PRODUCT_RESOURCE);
		resource.setName(file.getName());
		resource.setUrl(accessDir);
		resource.setResCode(sequenceService.getNextSequence(Resources.class));
		resource.setIsdelete(new Integer(0));
		this.resourceService.saveResource(resource);
	}

	/**
	 * 
	 * @return
	 */
	public List<Map<String, Object>> getProductStatus() {
		if (productStatus == null) {
			productStatus = new ArrayList<Map<String, Object>>();
			productStatus = ProductStatu.getProductStatus();
		}
		return productStatus;
	}

	/**
	 * 
	 * @param productStatus
	 */
	public void setProductStatus(List<Map<String, Object>> productStatus) {
		this.productStatus = productStatus;
	}

}
